<?php
session_start();
require("../includes/dbInfo.php");

/* Add an Item to the cart
*/
function addToCart($userID, $productID, $quantity) {      
    // does the product exist ? 
    $sql = "SELECT * FROM products WHERE productID = '$productID'"; 
    $result = mysql_query($sql) or die(mysql_error()); 
     
    if (mysql_num_rows($result) == 0) { 
        // the product doesn't exist 
        die("invalid product id: $productID.");
    }          
          
    // check if the product is already in cart table for this user 
    $sql = "SELECT * FROM cart WHERE productID = '$productID' AND userID = '$userID'"; 
    $result = mysql_query($sql) or die(mysql_error()); 

    if (mysql_num_rows($result) == 0) { 
        // put the product in cart table 
        $sql = "INSERT INTO cart (cartID, productID, userID, quantity) 
                VALUES (NULL, '$productID', '$userID', '$quantity')"; 
        $result = mysql_query($sql) or die(mysql_error()); 
    } else { 
        // update product quantity in cart table 
        $sql = "UPDATE cart SET quantity= quantity + '$quantity' WHERE userID = '$userID' AND productID = '$productID'";                         
        $result = mysql_query($sql) or die(mysql_error());         
    }                         
} 


/* 
    Remove an item from the cart 
*/ 
function deleteFromCart($userID, $productID) {

    $sql  = "DELETE FROM cart WHERE productID = '$productID' AND userID = '$userID'"; 
    $result = mysql_query($sql) or die(mysql_error());       
} 


/* Remove an entire cart (we have checked-out or cancelled)
*/
function removeCart($userID) { 
    if( $userID ) {
        $sql  = "DELETE FROM cart WHERE userID = '$userID'"; 
        $result = mysql_query($sql) or die(mysql_error());          

    }
}
?>